<?
//----------------------------------------------------------------------------------------
function G2U($str)
{
	$str = str_replace('[','&#',$str);
	$str = str_replace(']',';',$str);
	preg_match_all("/[\x80-\xff]?./",$str,$ar);
	$var="";
	foreach($ar[0] as $v)
	$var.="&#".switch_utf8_unicode(mb_convert_encoding($v,"UTF-8","GBK")).";";
	return $var;
}

function switch_utf8_unicode($c)
{
	switch(strlen($c))
	{
		case 1:
			return ord($c);
		case 2:
			$n = (ord($c[0]) & 0x3f) << 6;
			$n += ord($c[1]) & 0x3f;
			return $n;
		case 3:
			$n = (ord($c[0]) & 0x1f) << 12;
			$n += (ord($c[1]) & 0x3f) << 6;
			$n += ord($c[2]) & 0x3f;
			return $n;
		case 4:
			$n = (ord($c[0]) & 0x0f) << 18;
			$n += (ord($c[1]) & 0x3f) << 12;
			$n += (ord($c[2]) & 0x3f) << 6;
			$n += ord($c[3]) & 0x3f;
			return $n;
	}
}
//----------------------------------------------------------------------------------------
function U2G($str)
{
	$str = rawurldecode($str);
	preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
	$ar = $r[0];
	foreach($ar as $k=>$v)
	{
		if(substr($v,0,2) == "%u")
		$ar[$k] = mb_convert_encoding(pack("H4",substr($v,-4)),"GBK","UCS-2");
		elseif(substr($v,0,3) == "&#x")
		$ar[$k] = mb_convert_encoding(pack("H4",substr($v,3,-1)),"GBK","UCS-2");
		elseif(substr($v,0,2) == "&#")
		{
			$ar[$k] = mb_convert_encoding(pack("n",substr($v,2,-1)),"GBK","UCS-2");
		}
	}
	return join("",$ar);
}
//----------------------------------------------------------------------------------------
function getmicrotime()
{
	list($usec, $sec) = explode(" ",microtime());
	return ((float)$usec + (float)$sec);
}
function get_date_time($temp_time=null)
{
	if($temp_time==null) $temp_time=time();
	$array_register_data=getdate($temp_time);
	$this_data_time=sprintf("%04d-%02d-%02d %02d:%02d:%02d", $array_register_data['year'],$array_register_data['mon'],$array_register_data['mday'],$array_register_data['hours'],$array_register_data['minutes'],$array_register_data['seconds']);
	return $this_data_time;
}
function get_time($temp_time=null)
{
	if($temp_time==null) $temp_time=time();
	$array_register_data=getdate($temp_time);
	$this_data_time=sprintf("%02d:%02d:%02d", $array_register_data['hours'],$array_register_data['minutes'],$array_register_data['seconds']);
	return $this_data_time;
}
//----------------------------------------------------------------------------------------
function get_domain($str)
{
	$temp=explode('/',$str);
	return 'http://'.$temp[2].'/';
}
function cutstr($str,$cutleng,$add_str='..')
{
	if($cutleng>=strlen($str))return $str;
	else return substr($str,0,$cutleng).chr(0).$add_str;
}
function set_cache_true($tpl_name,$cache_time=null)
{
	global $tpl,$time_start,$tpl_id;
	$tpl_id=substr(md5(str_replace('&update_cache','',$GLOBALS['_SERVER']['PHP_SELF'].$GLOBALS['_SERVER']['QUERY_STRING'])),0,16);
	if(count($GLOBALS['_POST'])>0) return $tpl_id;
	if($cache_time==null) $cache_time=CACHE_LIFETIME;
	$tpl->caching=true;
	$tpl->cache_lifetime=$cache_time;
	if(isset($GLOBALS['_GET']['update_cache']) || $cache_time==-1)
	$tpl->clear_cache($tpl_name,$tpl_id);
	if($tpl->is_cached ($tpl_name,$tpl_id))
	{
		$tpl->display($tpl_name,$tpl_id);
		echo '<!--'.(getmicrotime()-$time_start).'-->';
		die();
	}
	return $tpl_id;
}
function is_localhost()
{
	if(!defined('ENVIRONMENT')) require_once('../kernel/include/environment_no_replace.inc.php');
	if(1==ENVIRONMENT) return false;
	else return true;
}
function del_all_cookies() {
	//del all cookies
	foreach ($_COOKIE as $value) {
		$key=key($_COOKIE);
		setcookie($key,false,time()-3600);
		next($_COOKIE);
	}
}
function check_login($url='index.php') 
{
	if(isset($_COOKIE['tovy_login']) && $_COOKIE['tovy_login']==1)
	{
		global $user;
		$user->user_name=$_COOKIE['user_name'];
		$user->nick_name=$_COOKIE['nick_name'];
		$user->vip=isset($_COOKIE['vip'])?$_COOKIE['vip']:0;
		$user->login=true;
		$user->user_init();
		return true;
	}
	if($url=='admin/index.php') return false;
	require_once ( 'x_passport.php' );

	$clsPassport = new x_Passport;
	$clsPassport->appId = 10; // 通行证服务ID
	$clsPassport->encryptKey = 'k4kfEOJdi9asUWKKSDXxCKDIfjsoUH5Aa09dnAB'; // 私钥
	$clsPassport->verify ();
	// 第二步，保存 Passport 信息到当前程序的 Session
	$userSession = $clsPassport->vars;
	if(isset($userSession['nickname']) && $userSession['nickname']!='')
	{
		global $user;
		$user->user_name=$userSession['username'];
		$user->nick_name=$userSession['nickname'];
		$user->vip=$user_level;
		$user->login=true;
		$user->user_init();
		setcookie('tovy_login',1,null,'/');
		setcookie('user_name',$user->user_name,null,'/');
		setcookie('nick_name',$user->nick_name,null,'/');
		setcookie('vip',$user->vip,null,'/');
		return true;
	}
}
function get_ip(){
	return getenv('REMOTE_ADDR');
}
//----------------------------------------------------------------------------------------
function error($msg,$line='',$flag=true)
{
	if(!ERROR_LOG_FLOG) return;
	$fp=fopen(PATH_lOG.'error.log','a+');
	$content=get_date_time()."\r\n\r\n";
	$content.=$msg."\r\n\r\n";
	if($flag=='sql') $content.="Mysql Error: ".mysql_error()."\r\n\r\n";
	$content.="Line:".$line."\r\n\r\n";
	fwrite($fp,$content);
	fclose($fp);
	die('error: '.$content);
}
function run_sql($sql,$line,$flagLog=true) {
	global $dbh;
	$t=getmicrotime();
	if(!$res=mysql_query($sql, $dbh)) return error($sql,$line,'sql');
	$t=getmicrotime()-$t;
	if($flagLog) {
		$flag=true;
		if(!$res) $flag=false;
		sql_log($sql,$flag,$line,$t);
	}
	return $res;
}
function sql_run($sql,$line,$flagLog=true) {
	global $dbh;
	$t=getmicrotime();
	if(!$res=mysql_query($sql, $dbh)) return error($sql,$line,'sql');
	$t=getmicrotime()-$t;
	if($flagLog) {
		$flag=true;
		if(!$res) $flag=false;
		sql_log($sql,$flag,$line,$t);
	}
	return $res;
}
function sql_get_one($sql,$line,$flagLog=true){
	$res=run_sql($sql,$line,$flagLog);
	return mysql_fetch_array($res,1);
}
function sql_get_arr($sql,$line,$flagLog=true,$get_style=1){
	$res=run_sql($sql,$line,$flagLog);
	$arr=array();
	$count=0;
	$row=mysql_fetch_array($res,$get_style);
	while ($row) {
		$arr[$count++]=$row;
		$row=mysql_fetch_array($res,$get_style);
	}
	if($count==0) return false;
	$arr['sql']['count']=$count;
	return $arr;
}
function sql_get($sql,$line,$flagLog=true){
	$res=run_sql($sql,$line,$flagLog);
	$arr=array();
	$count=0;
	$row=mysql_fetch_array($res,1);
	while ($row) {
		$arr[$count++]=$row;
		$row=mysql_fetch_array($res,1);
	}
	if($count==0) return false;
	return $row;
}
$debug_sql_write_flag=1;
$myLogLevelStatic=5;
$myLogLevel=$myLogLevelStatic;
$myLogTab=3; //缩进距离
function sql_log($sql,$flag,$row,$time) {
	global $debug_sql_write_flag,$myLogLevel,$myLogLevelStatic,$myLogTab;
	if(!SQL_LOG_FLOG && $time < 0.05) return;
	$flag=($flag)?'~~~~':'!!!!';
	$fp=fopen(PATH_lOG.'sql.log','a+');
	if($debug_sql_write_flag) {
		$debug_sql_write_flag=0;
		fwrite($fp,"*********************************************************************************\r\n\r\n");
	}
	$space=str_pad('',($myLogLevelStatic-$myLogLevel)*$myLogTab,' ');
	$content=$space.get_date_time()."\r\n";
	$content.=$space."Line: ".$row.'  Time:'.$time.'  '.$flag.":\r\n".$space.$sql."\r\n\r\n";
	fwrite($fp,$content);
	fclose($fp);
}
function myLog($msg,$flag=0) {
	global $debug_sql_write_flag,$myLogLevel,$myLogLevelStatic,$myLogTab;
	if(!SQL_LOG_FLOG) return;
	$fp=fopen(PATH_lOG.'sql.log','a+');
	if($debug_sql_write_flag) {
		$debug_sql_write_flag=0;
		fwrite($fp,"*********************************************************************************\r\n\r\n");
	}
	if($flag ==1) {
		$myLogLevel++;
		$space=str_pad('',($myLogLevelStatic-$myLogLevel)*$myLogTab,' ');
		$str=str_pad('', $myLogLevel*$myLogTab,'-');
		fwrite($fp,"$space$str -结束- $msg $str\r\n\r\n");
	}else {
		$space=str_pad('',($myLogLevelStatic-$myLogLevel)*$myLogTab,' ');
		$str=str_pad('', $myLogLevel*$myLogTab,'-');
		fwrite($fp,"$space$str -开始- $msg $str\r\n\r\n");
		$myLogLevel--;
	}
	fclose($fp);
	return;
}
function js_alert($msg='',$back=false,$url='') {
	if($msg!='') {
		echo '<script language="javascript" >
		';
		echo "alert('$msg');
		";
		if($url!='') echo 'window.location="'.$url.'";
		';
		else {
			if(strcmp($back,'close')+1) echo 'window.close();';
			else if($back==true) echo 'window.history.back(-1);';
		}
		echo '
		</script>';
		if($back) die();
	}
}
function get_self(){
	$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
	return $url;
}
function sql_filter($value) {
	return htmlspecialchars(addslashes($value));
}
function to_url($url) {
	$now_url=substr($_SERVER['PHP_SELF'],1);
	$target_url=explode('?',$url);
	$target_url=$target_url[0];
	$now_url=explode('/',$now_url);
	$now_url=$now_url[count($now_url)-1];	
	if($now_url != $target_url) {
		header('location:'.$url);
		//add do -> close all mysql link:
		//end.
		//echo "<A href='$url'>返回</A>";
		//header('location:'.$url);
		exit();
	}
}
function filter_str($str){
	$filter='妈逼 草你妈 烂逼 烂货 贱逼 狗B 狂操 狗操 狗娘 贱货 贱比 靠你妈 强奸 干你妈 干你娘 干你爷爷';
	$arr=explode(' ',$filter);
	foreach ($arr as $value) {
	
		$str=str_replace($value,'(我爱武林三国)',$str);
	}
	return $str;
}
function globalCutStr($str, $slen, $startdd = 0, $code = 'UTF-8')
{
	ini_set('memory_limit', '-1');
    if($code == 'UTF-8') 
    { 
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/"; 
		preg_match_all($pa, $str, $t_string); 
        if(count($t_string[0]) - $startdd > $slen) return join('', array_slice($t_string[0], $startdd, $slen)); 
        return join('', array_slice($t_string[0], $startdd, $slen)); 
    } 
    else 
    { 
        $startdd = $startdd*2; 
        $slen = $slen*2; 
        $strlen = strlen($str); 
        $restr = ''; 
        for($i=0; $i<$strlen; $i++) 
        { 
            if($i>=$startdd && $i<($startdd+$slen)) 
            { 
                if(ord(substr($str, $i, 1))>129) 
                { 
                    $restr.= substr($str, $i, 2); 
                } 
                else 
                { 
                    $restr.= substr($str, $i, 1); 
                } 
            } 
            if(ord(substr($str, $i, 1))>129) $i++; 
        } 
        return $restr; 
    } 
} 
?>